package com.aisino.inveli.vinda.controller;

import com.aisino.inveli.vinda.entity.ConfigEntity;
import com.aisino.inveli.vinda.entity.Customer;
import com.aisino.inveli.vinda.service.ConfigService;
import com.aisino.inveli.vinda.service.CustomerService;
import com.aisino.inveli.vinda.task.CustomerTask;
import com.aisino.inveli.vinda.utils.AlertUtil;
import com.aisino.inveli.vinda.utils.ProgressUtil;
import com.aisino.inveli.vinda.utils.TxtUtil;
import com.aisino.inveli.vinda.VindamanagerApplication;
import com.aisino.inveli.vinda.entity.TxtEntity;
import de.felixroske.jfxsupport.FXMLController;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.*;

import javax.annotation.Resource;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @author leifeng
 * @Date 2017-11-10
 **/
@FXMLController
public class MainController implements Initializable {

    // ----------------------txt_tableView-------------------------
    @FXML
    private TableView<TxtEntity> tvTxt;
    @FXML
    private TableColumn<TxtEntity,Integer> idCol;
    @FXML
    private TableColumn<TxtEntity,String> nameCol;
    @FXML
    private TableColumn<TxtEntity,String> pathCol;

    // ----------------------------折扣模式-----------------------------
    @FXML
    private CheckBox isSup;
    @FXML
    private CheckBox isMon;

    // ----------------------------GridPane-------------------------------
    @FXML
    private ComboBox<String> isRateBox;
    @FXML
    private ComboBox<Double> rateBox;
    @FXML
    private TextField payee;
    @FXML
    private TextField checker;
    @FXML
    private TextField discount;
    @FXML
    private TextField handler;
    @FXML
    private TextField salesBank;
    @FXML
    private TextField salesAddress;
    @FXML
    private TextField salesName;
    @FXML
    private TextField regNumber;
    @FXML
    private TextField salesTel;

    // ----------------------service-------------------------------
    @Resource
    private ConfigService configService;
    @Resource
    private CustomerService customerService;

    // -----------------------------页面功能实现----------------------------------------

    /**
     * 跳转下一页
     * @param event
     */
    @FXML
    public void goNextView(ActionEvent event){
        Window window = ((Button) event.getSource()).getScene().getWindow();
        TxtEntity selectedItem = tvTxt.getSelectionModel().getSelectedItem();
        // 1.获取选中txt文件
        if (selectedItem == null) {
            AlertUtil.showErrAlert("请选择一个需要转换的文件",window,"跳转失败");
            event.consume();
            return;
        }
        // 2.保存当前界面设置
        ConfigEntity configEntity = configService.findConfigById(1);
        if (configEntity == null ){
            configEntity = new ConfigEntity();
            configEntity.setId(1);
        }
        // 2.1保存折扣模式
        configEntity.setIsSup(isSup.selectedProperty().getValue()==null?false:isSup.selectedProperty().getValue());
        configEntity.setIsMon(isMon.selectedProperty().getValue()==null?false:isMon.selectedProperty().getValue());
        // 2.2保存GridPane
        configEntity.setIsRate(isRateBox.getValue().equals("含税")?true:false);
        configEntity.setRate(rateBox.getValue());
        configEntity.setChecker(checker.getText());
        configEntity.setPayee(payee.getText());
        configEntity.setDiscount(discount.getText().equals("")?0.00:Double.parseDouble(discount.getText()));
        configEntity.setHandler(handler.getText());
        configEntity.setRegNumber(regNumber.getText());
        configEntity.setSalesName(salesName.getText());
        configEntity.setSalesAddress(salesAddress.getText());
        configEntity.setSalesBank(salesBank.getText());
        configEntity.setSalesTel(salesTel.getText());
        // 2.3保存选中的数据和折扣金额
        configEntity.setSelectPath(selectedItem.getTxtPath());
        System.out.println(selectedItem.getTxtPath());
        // 2.4保存到数据库
        configEntity.setId(1);
        configService.save(configEntity);
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/next.fxml"));
        VindamanagerApplication.showView(fxmlLoader);
    }

    /**
     * 客户信息维护
     * @param event
     */
    @FXML
    public void saveCustomAction(){
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/customer.fxml"));
        VindamanagerApplication.showView(fxmlLoader);
    }

    /**
     * 设置文件输入路径
     * @param event
     */
    public void setInPathAction(ActionEvent event){
        // 1.获取文件所属窗体
        Window window  = ((MenuItem)event.getSource()).getParentPopup().getOwnerWindow();
        // 2.文件选择框
        DirectoryChooser fileChooser = new DirectoryChooser();
        // 2.1获取上次记录文件夹路径
        fileChooser.setTitle("设置txt文件路径");
        ConfigEntity config = configService.findConfigById(1);
        if (config!=null&&config.getInputPath() != null) {
            fileChooser.setInitialDirectory(new File(config.getInputPath()));
        }
        File file = fileChooser.showDialog(window);
        // 3.判断设置路径
        if(file != null){
            // 3.2路径正确则将当前路径下的txt文档显示到txt_tv上
            List<TxtEntity> txtEntityList = TxtUtil.parsePath(file);
            showTxtTableView(txtEntityList);
            // 3.3将路径update到h2 database中
            configService.updateInputPath(file.getPath());
            // 3.4弹出设置成功提示框
            AlertUtil.showInfoAlert("Txt文件路径："+file.getPath(),"设置成功",window);
        }
    }



    /**
     * 设置文件输出路径
     * @param event
     */
    public void setOutPathAction(ActionEvent event){
        // 1.获取文件所属窗体
        Window window  = ((MenuItem)event.getSource()).getParentPopup().getOwnerWindow();
        // 2.文件选择框
        DirectoryChooser fileChooser = new DirectoryChooser();
        // 2.1获取上次记录文件夹路径
        fileChooser.setTitle("设置输出Excel文件路径");
        ConfigEntity config = configService.findConfigById(1);
        if (config!=null&&config.getOutputPath() != null) {
            fileChooser.setInitialDirectory(new File(config.getOutputPath()));
        }
        File file = fileChooser.showDialog(window);
        // 3.判断设置路径
        if(file != null){
            // 3.2将路径update到h2 database中
            configService.updateOutputPath(file.getPath());
            // 3.3弹出设置成功提示
            AlertUtil.showInfoAlert("Excel保存路径："+file.getPath(),"设置成功",window);
        }
    }

    /**
     * 打开单独一个文件
     * @param event
     */
    @FXML
    public void openFileAction(ActionEvent event){
        // 1.获取文件所属窗体
        Window window  = ((MenuItem)event.getSource()).getParentPopup().getOwnerWindow();
        // 2.弹出文件选择框
        FileChooser fileChooser = new FileChooser();
        // 2.1文件筛选
        List<String> filter = new ArrayList<>();
        filter.add("*.txt");
        FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("txt files (*.txt)", filter);
        fileChooser.getExtensionFilters().add(extFilter);
        fileChooser.setTitle("选择打开文件");
        // 2.2保存单个文件选择
        ConfigEntity config = configService.findConfigById(1);
        if (config!=null&&config.getSinglePath() != null) {
            fileChooser.setInitialDirectory(new File(config.getSinglePath()));
        }
        File file = fileChooser.showOpenDialog(window);
        if(file != null){
            // 3.1.选择文件成功则保存此文件路径,同时将selectPath保存为当前路径
            configService.updateSinglePath(file);
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/next.fxml"));
            VindamanagerApplication.showView(fxmlLoader);
        }
    }

    /**
     * 刷新重新加载tvTxt
     * @param event
     */
    @FXML
    public void refreshAction(ActionEvent event){
        // 1.获取文件所属窗体
        Window window  = ((Button)event.getSource()).getScene().getWindow();
        // 2.查询数据库中txt文件路径
        ConfigEntity config = configService.findConfigById(1);
        File file = new File(config.getInputPath());
        List<TxtEntity> txtEntityList = TxtUtil.parsePath(file);
        // 3.重新初始化tvTxt
        showTxtTableView(txtEntityList);
        AlertUtil.showInfoAlert("","刷新成功",window);
    }

    /**
     * 退出程序操作
     * @param event
     */
    @FXML
    public void exitAction(ActionEvent event){
        Window window = ((MenuItem) event.getSource()).getParentPopup().getOwnerWindow();
        Boolean flag = AlertUtil.confirmAlert("确认退出",window,"是否退出程序");
        if (flag) {
            Platform.exit();
            System.exit(0);
        }else{
            event.consume();
        }
    }

    /**
     * 界面初始化操作
     * @param location
     * @param resources
     */
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        ConfigEntity config = configService.findConfigById(1);
        // 设置金额模式comboBox
        isRateBox.getItems().addAll("含税");
        isRateBox.setValue("含税");
        // 设置税率comboBox
        rateBox.getItems().addAll(0.17);
        rateBox.setValue(0.17);
        if (config != null){
            // 设置收款人、复核人
            payee.setText(config.getPayee());
            checker.setText(config.getChecker());
            // 设置折扣模式
            isSup.setSelected(config.getIsSup());
            isMon.setSelected(config.getIsMon());
            //设置企业信息
            regNumber.setText(config.getRegNumber());
            salesAddress.setText(config.getSalesAddress());
            salesBank.setText(config.getSalesBank());
            salesName.setText(config.getSalesName());
            salesTel.setText(config.getSalesTel());
            handler.setText(config.getHandler());
            // 加载tvTxt
            if (config.getInputPath() != null) {
                File file = new File(config.getInputPath());
                List<TxtEntity> txtEntityList = TxtUtil.parsePath(file);
                showTxtTableView(txtEntityList);
            }
        }
    }

    // ----------------------------------界面其他初始化-------------------------------------

    /**
     * 初始化txt_tableView
     * @param txtEntityList
     */
    private void showTxtTableView(List<TxtEntity> txtEntityList) {
        idCol.setCellValueFactory(new PropertyValueFactory<>("id"));
        pathCol.setCellValueFactory(new PropertyValueFactory<>("txtPath"));
        nameCol.setCellValueFactory(new PropertyValueFactory<>("txtName"));
        ObservableList<TxtEntity> list = FXCollections.observableArrayList();
        for (TxtEntity txtEntity:
                txtEntityList) {
            list.add(txtEntity);
        }
        tvTxt.setItems(list);
    }


}
